<?php

namespace plugin\ai_invitation\app\controller;

use GuzzleHttp\Exception\GuzzleException;
use Overtrue\Socialite\Exceptions\AuthorizeFailedException;
use support\Request;
use support\Response;

class IndexController
{

    public $config;

    public function __construct()
    {
        $this->config = config('plugin.sns.wechat');
    }

    /**
     * 登录
     * @param Request $request
     * @return string|Response
     */
    public function index(Request $request)
    {
        if ($this->config['wechat']['enable']) {
            $user = session('user');
            if ($request->path() == '/' && empty($this->config['wechat']['redirect'])){
                return '微信登录地址和登录成功后重定向地址不能相同';
            }
            $home = empty($this->config['wechat']['redirect']) ? '/' : $this->config['wechat']['redirect'];
            if ($user) {
                return redirect($home);
            }
            return view('/index/index', compact('home'));
        }
        return "未开启微信登录功能";
    }

    /**
     * 生成授权链接并跳转
     * @param Request $request
     * @param string $type
     * @return string|Response
     */
    public function auth(Request $request, string $type = 'wechat')
    {
        if (!$this->config[$type]['enable']){
            return "未开启微信登录功能";
        }
        $url = $request->header('x-forwarded-proto') . '://' . $request->host();
        $redirectUrl = $url . route('wechat.auth.callback');
        $authorizer = (new Wechat())->getAuthUrl($redirectUrl, $type);
        return redirect($authorizer);
    }
    /**
     * 模式二公众号事件回调
     * @param Request $request
     * @return false|string
     */
    public function eventCallback(Request $request)
    {
        $wechat = new Wechat();
        return $wechat->eventCallback($request);
    }

    /**
     * 授权回调
     * @param Request $request
     * @return string|Response
     */
    public function callback(Request $request)
    {
        $code = $request->get('code');
        $state = $request->get('state');
        if (empty($code)) {
            return '授权失败：无效的code';
        }

        try {
            $userInfo = Wechat::userFromCode($code,$state);
        } catch (GuzzleException|AuthorizeFailedException $e) {
            return '获取用户信息失败，' . $e->getMessage();
        }

        // 虚拟账号时不进行登录
        if (isset($userInfo['raw']['is_snapshotuser'])){
            $home = empty($this->config['redirect']) ? "/" : $this->config['redirect'];
            return redirect($home);
        }

        if ($this->config['platform']['enable'] && !isset($userInfo['raw']['unionid'])){
            return '配置错误：开启了开放平台登录，但未将公众号授权给开放平台';
        }

        if ($this->config['platform']['enable']){
            $snsUser = SnsUser::with('base')->where('union_id', $userInfo['raw']['unionid'])->first();
        } else {
            $snsUser = SnsUser::with('base')->where('open_id', $userInfo->getId())->first();
        }

        if ($snsUser) {
            if ($snsUser->base->status == 0) {
                // 登录账号
                $request->session()->set('user', [
                    'id' => $snsUser->base->id,
                    'username' => $snsUser->base->username,
                    'nickname' => $snsUser->base->nickname,
                    'avatar' => $snsUser->base->avatar,
                    'email' => $snsUser->base->email,
                    'mobile' => $snsUser->base->mobile,
                ]);
            } else {
                return '登录失败：账号已被禁用';
            }
        } else {
            // 创建账号
            $time = time();
            // 下载头像
            $imageData = file_get_contents($userInfo->getAvatar());
            // 指定本地保存路径
            $localPath = sns_public_path("/avatar/{$time}.jpg");
            // 前端访问路径
            $staticPath = sns_static_path("/avatar/{$time}.jpg");
            // 将图片内容保存到本地文件
            file_put_contents($localPath, $imageData);
            // 创建系统账号
            $waUser = new BaseUser();
            $waUser->username = $userInfo->getNickname() . substr(uniqid(), -6);
            $waUser->nickname = $userInfo->getNickname();
            $waUser->password = 'wechat_user';
            $waUser->join_time = date('Y-m-d H:i:s', $time);
            $waUser->join_ip = $request->getRealIp();
            $waUser->avatar = $staticPath;
            $waUser->save();
            // 创建SNS账号
            $snsUser = new SnsUser();
            $snsUser->user_id = $waUser->id;
            $snsUser->open_id = $userInfo->getId();
            $snsUser->union_id = $userInfo['raw']['unionid'] ?? '';
            $snsUser->save();
            $request->session()->set('user', [
                'id' => $waUser->id,
                'username' => $userInfo->getNickname() . substr(uniqid(), -6),
                'nickname' => $userInfo->getNickname(),
                'avatar' => $staticPath,
            ]);
        }

        $home = empty($this->config['redirect']) ? "/" : $this->config['redirect'];
        return redirect($home);
    }
    
    public function setMenu(){
        $app = (new Wechat())->app();
        $current = $app->menu->current();
        $buttons = [
            [
                "type" => "view",
                "name" => "AI聊天",
                "url"  => "https://ai.codepoch.com"
            ],
            [
                "type" => "click",
                "name" => "领取兑换码",
                "key" => "兑换码"
            ],
        ];
        $res = $app->menu->create($buttons);
        var_dump($res);
    }
}
